package servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import pojo.BuyTicket;
import pojo.Ticket;
import service.TicketService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 用户线上购票
 * 输入一个ticket对象将其插入到数据库中
 * 最后一定返回true（其实反不返回无所谓，前端默认插入成功）
 */
@WebServlet("/buyTicketOnlineServlet")
public class BuyTicketOnlineServlet extends HttpServlet {
    private final TicketService service = new TicketService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jsonString = request.getReader().readLine();
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        String jsonTicket = jsonObject.getJSONObject("ticket").toString();
        String jsonBuyTicket = jsonObject.getJSONObject("buyTicket").toString();

        Ticket ticket = JSON.parseObject(jsonTicket, Ticket.class);
        BuyTicket buyTicket = JSON.parseObject(jsonBuyTicket, BuyTicket.class);

        long ticketNo = service.addOneTicket(ticket);
        buyTicket.set_ticketNo(ticketNo);
        service.addOneBuyTicket(buyTicket);

        jsonString = JSON.toJSONString(true);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
